<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap[mode]" v-model="visible" :width="980" destroy-on-close @closed="$emit('closed')">
        <div class="tipsbox">
            <div class="tips-title"></div>
        </div>
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100px" label-position="right" v-loading="loading">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="①课程类型" prop="courseType">
                        体验课
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="②学员姓名" prop="userId">
                        {{ transaction?.fromUser?.name }}
                    </el-form-item>
                    
                </el-col>
                <el-col :span="8">
                    <el-form-item label="③交付方式" prop="listenType">
                        <el-select v-model="form.listenType" placeholder="请选择交付方式" clearable filterable style="width: 100%;">
                            <el-option label="线上" :value="1"></el-option>
                            <el-option label="机构" :value="2"></el-option>
                            <el-option label="上门" :value="3"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="④课程名称" prop="courseId" v-if="form.courseType == 4">
                        <el-select v-model="form.courseId" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option :label=" item.course ? item.course.name : item.name" :value="item.course ? item.course.id : item.id" v-for="item in userCourses">
                                <span style="float: left;">{{ item.course ? item.course.name : item.name }}</span>
                                <span style="float: right; color: red;" v-if="item.course">{{ item.course.learnNum + '/' + item.course.words }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="⑤上课日期" prop="startDate">
                        <el-date-picker
                            clearable
                            v-model="form.startDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="选择日期"
                            :disabled-date="disabledDate"
                            @change="selectDateFun"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="⑥上课时间" prop="startTime">
                        <el-time-select
                        v-model="form.startTime"
                        :start="startTime"
                        step="00:30"
                        :end="endTime"
                        placeholder="选择时间"
                        @change="selectTimeFun"
                        >
                        </el-time-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="⑥教练姓名" prop="teacherId">
                        <el-select v-model="form.teacherId" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option :label="item.name" :value="item.id" v-for="item in teacherList"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>   
            </el-row>        
            
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">{{ form.id ? '保 存' : '立即创建' }}</el-button>
        </template>
    </el-dialog>

    <courseSelectDom 
		ref="courseSelectDom" 
		@submit="submitAddCourse" 
		v-if="dialog.course" 
		@close="dialog.course = false"
        :userId="form.userId"
		:treeSearch="{type: '2'}"
		:defaultSearch="{containLearnNum: 1, courseStatus: '1', status: '1', userId: form.userId}"
	></courseSelectDom>

</template>

<script>
import courseSelectDom from './courseSelectDom.vue'
export default {
    emits: ['success', 'closed'],
    components: {
		courseSelectDom
	},
    props: {
        agentName: {
            type: String,
            default: ''
        },
        categoryData: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '创建预约',
                show: '查看'
            },
            dialog: {
                course: false,
			},
            loading: false,
            visible: false,
            userLoading: false,
            isSaveing: false,
            //表单数据
            form: this.getDefaultRuleForm(),
            //验证规则
            rules: {
                listenType: [
                    { required: true, message: '请选择交付方式', trigger: 'change' },
                ],
                startDate: [
                    { required: true, message: '请选择上课日期', trigger: 'change' },
                ],
                startTime: [
                    { required: true, message: '请选择上课时间', trigger: 'change' },
                ],
                teacherId: [
                    { required: true, message: '请选择教练', trigger: 'change' },
                ],
            },
            userList: [],
            userCourses: [],
            appointmentNumbers: 0, //可预约次数
            teacherList: [],
            chooseAgentId: 0,
            startTime: '',
            endTime: '',
            selectedCourses: [],
            transaction: null
        }
    },
    mounted() {
        this.getCourseCategory()
    },
    methods: {
        //显示
        open(mode = 'add', row) {
            this.mode = mode;
            this.transaction = row
            if (row.transactionTeacher?.teacher?.id) {
                this.form.teacherId = row.transactionTeacher?.teacher?.id
                this.teacherList = [{id: row.transactionTeacher?.teacher?.id, name: row.transactionTeacher?.teacher?.name}]
            }
            this.chooseAgentId = row?.fromUser?.agent?.id
            this.visible = true;
            return this
        },
        getCourseCategory() {
            this.$API.course.category.all.get({
            }).then((res) => {
                this.userCourses = res.data
            })
        },
        //选择课程弹窗
        addCourseFun(){
            if (!this.form.userId) {
                this.$notify.error('请先选择学员')
                return false
            }
            this.dialog.course = true
            this.$nextTick(() => {
                let arr = JSON.parse(JSON.stringify(this.selectedCourses))
                this.$refs.courseSelectDom.open(arr || [])
            })
		}, 
        async submitAddCourse(data) {
            let ids = data.map(item => { return item.course.id })
            this.dialog.course = false
            this.form.courseId = ids[0]
            this.selectedCourses = data
        },
        selectDateFun(row) {
            if (this.form.startDate) {
                this.getTeacherListHander()
            }
            let today = new Date()
            let month = today.getMonth() + 1
            if (month < 10) {
                month = '0' + month
            }
            let date = today.getDate()
            if (date < 10) {
                date = '0' + date
            }
            let todayStr = today.getFullYear() + '-' + month + '-' + date
            if (this.form.startDate == todayStr) {
                //判断当前时间是否超过半小时
                let nowTime = today.getMinutes()
                let hours = today.getHours() 
                if (hours < 23) {
                    if (nowTime > 30) {
                        hours = hours + 1
                        if (hours < 10) {
                            hours = '0' + hours
                        }
                        this.startTime = hours + ':00'
                        this.endTime = '23:00'
                    }else{
                        if (hours < 10) {
                            hours = '0' + hours
                        }
                        this.startTime = hours + ':30'
                        this.endTime = '23:00'
                    }
                }
            }else{
                this.startTime = '00:00'
                this.endTime = '23:00'
            }
        },
        selectTimeFun(row) {
            if (this.form.startDate) {
                this.getTeacherListHander()
            }
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                }

                let data = {}
                for (let key in this.form) {
                    if (key == 'startData' || key == 'startTime') {
                        continue
                    }
                    data[key] = this.form[key]
                }

                data.courseType = 4
                data.userId = this.transaction.fromUser.id
                if (this.form.courseType == 4) {
                    data.courseId = 0
                    data.courseCategoryId = this.form.courseId
                }
                data.startTime = this.form.startDate + ' ' + this.form.startTime
                data.transactionCode = this.transaction.code
                try {
                    this.isSaveing = true;
                    await this.$API.transaction.addAppointment.post(data)
                    this.$emit('success', this.form, this.mode)
                    this.visible = false;
                    this.$notify.success("保存成功")
                } finally {
                    this.isSaveing = false;
                }
            })
        },
        getDefaultRuleForm() {
            return {
                id: null,
                userId: '',
                teacherId: '',
                courseId: '',
                courseType: 4,
                listenType: '',
                startDate: '',
                startTime: '',
                transactionCode: ''
            }
        },
        getTeacherListHander() {
            if (this.transaction?.transactionTeacher?.teacher?.id) {
                return
            }
            let startTime = ''
            if (this.form.startDate && this.form.startTime) {
                startTime = this.form.startDate + ' ' + this.form.startTime
            }else if (this.form.startDate) {
                startTime = this.form.startDate
            }
            this.$API.teacher.appointmentList.get({
                startTime: startTime,
                agentId: 0,
            }).then((res) => {
                this.teacherList = res.data
            })
        },
        //禁用今天之前的日期
        disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
        }
    }
}
</script>

<style scoped>
.tipsbox {
    position: relative;
    left: 16px;
    bottom: 10px;
}

.tips-title {
    color: red; 
    margin-left: 20px; 
    margin-bottom: 10px; 
    font-size: 18px; 
    font-weight: bold;
}

.tips-con {
    color: red; 
    margin-left: 20px; 
    margin-bottom: 10px; 
    font-size: 14px; 
    font-weight: bold;
}

</style>
